package com.songcan.basics.core.service.impl;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.internal.OSSUtils;
import com.aliyun.oss.model.OSSObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.songcan.basics.core.service.AttachmentService;
import com.songcan.basics.core.service.CommonFileService;
import com.songcan.basics.properties.OssProperties;
import com.songcan.common.contans.ImageType;
import com.songcan.common.exception.ObjectNotException;
import com.songcan.common.exception.ParamNotException;
import com.songcan.common.utils.MimeTypeUtil;
import com.songcan.model.basics.Attachment;
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;

@Service
public class CommonFileServiceImpl implements CommonFileService {

    private AttachmentService attachmentService;
    private OssProperties ossProperties;

    @Autowired
    private CommonFileServiceImpl(AttachmentService attachmentService,OssProperties ossProperties){
        this.attachmentService = attachmentService;
        this.ossProperties = ossProperties;
    }

    @Override
    public Long addFile(MultipartFile multipartFile, ImageType imageType) throws IOException {

        Attachment attachment  = new Attachment();

        String contentType = multipartFile.getContentType();
        String prefix = IdWorker.get32UUID();
        File file = File.createTempFile(prefix,null);
        multipartFile.transferTo(file);
        String format = MimeTypeUtil.getExtFromContentType(contentType);
        if(StrUtil.isEmpty(format)){
            throw new ParamNotException("不支持类型");
        }
        attachment.setContentType(contentType);
        attachment.setFormat(format);

        attachment.setCreateTime(new Date());
        attachment.setName(prefix);
        attachment.setOriginalFileName(multipartFile.getOriginalFilename());
        Long id = IdWorker.getId();
        attachment.setId(id);
        String key =prefix;
        String name = attachment.getOriginalFileName();
        if(Objects.nonNull(name)&&name.contains(".")){
            key+=MimeTypeUtil.getExtFromFileName(name);
        }else{
            key+=MimeTypeUtil.getExtFromContentType(contentType);
        }
        switch (imageType) {
            case IMAGE: {
                key = ossProperties.getImagePath() + key;
            }
            break;
            case STORE: {
                key = ossProperties.getStorePath() + key;
            }
            break;
            case QRCODE:{
                key = ossProperties.getQrCodePath() + key;
            }
            break;
            case MERCHANT:{
                key = ossProperties.getMerchantPath() + key;
            }
            break;
        }
        putObjects(key,file);
        FileUtils.deleteQuietly(file);
        attachmentService.save(attachment);
        return  id;
    }


    private void putObjects(String key,File file){
        OSS client = new OSSClientBuilder().build(ossProperties.getEndPoint(),ossProperties.getKeyId(),ossProperties.getKeySecret());
        client.putObject(ossProperties.getBucket(),key,file);
        client.shutdown();
    }


    @Override
    public void get(String id,ImageType imageType, HttpServletResponse response) throws IOException {
        Attachment attachment = attachmentService.getById(id);
        if(Objects.isNull(attachment)){
            throw new ObjectNotException("资源不存在");
        }
        String key = attachment.getName();
        String contentType = attachment.getContentType();

        if(key.contains(".")){
            key += MimeTypeUtil.getExtFromFileName(key);
        }else{
            key += MimeTypeUtil.getExtFromContentType(contentType);
        }


        response.setContentType(contentType+";charset=utf-8");
        writeObject(key,response,ossProperties.getBucket(),imageType);
    }

    private void writeObject(String key, HttpServletResponse response, String bucket,ImageType imageType) throws IOException {
//        if(imageType == ImageType.IMAGE) {
//            key = ossProperties.getImagePath() + key;
//        }
//        if(imageType == ImageType.QRCODE){
//            key = ossProperties.getQrCodePath() + key;
//        }
//        if(imageType == ImageType.MERCHANT){
//            key = ossProperties.getMerchantPath() + key;
//        }
//        if(imageType == ImageType.STORE){
//            key = ossProperties.getStorePath() + key;
//        }
        switch (imageType) {
            case IMAGE: {
                key = ossProperties.getImagePath() + key;
            }
            break;
            case STORE: {
                key = ossProperties.getStorePath() + key;
            }
            break;
            case QRCODE:{
                key = ossProperties.getQrCodePath() + key;
            }
            break;
            case MERCHANT:{
                key = ossProperties.getMerchantPath() + key;
            }
            break;
        }
        OSS client = new OSSClientBuilder().build(ossProperties.getEndPoint(), ossProperties.getKeyId(), ossProperties.getKeySecret());
        OSSObject ossObject;
        ossObject = client.getObject(bucket, key);
        write(ossObject, response);
        client.shutdown();
    }

    private void write(OSSObject ossObject, HttpServletResponse response) throws IOException {
        OutputStream outputStream = response.getOutputStream();
        IOUtils.copy(ossObject.getObjectContent(), response.getOutputStream());
        outputStream.flush();
        outputStream.close();
    }
}
